﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Net;
using System.ComponentModel;

public class WebDownloader
{
    private class Downloadable
    {
        public string url;
        public string path;

        public Downloadable(string url, string path)
        {
            this.url = url;
            this.path = path;
        }
    }

    private Queue<Downloadable> queue;
    public WebClient downloader;
    private static WebDownloader instance;

    private WebDownloader()
    {
        queue = new Queue<Downloadable>();
        downloader = new WebClient();
        downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
    }

    private void Completed(object sender, AsyncCompletedEventArgs e)
    {
        if (queue.Count > 0)
        {
            StartDownload(queue.Dequeue());
        }
    }

    public static WebDownloader current
    {
        get
        {
            if (instance == null)
            {
                instance = new WebDownloader();
            }
            return instance;
        }
    }

    private void StartDownload(Downloadable toDownload)
    {
        downloader.DownloadFileAsync(new Uri(toDownload.url), toDownload.path);
    }

    public void DownloadFile(string url, string path)
    {
        Downloadable toDownload = new Downloadable(url, path);
        if (!downloader.IsBusy)
        {
            StartDownload(toDownload);
        }
        else
        {
            queue.Enqueue(toDownload);
        }
    }

    public void CancelAll()
    {
        queue.Clear();
        downloader.CancelAsync();
    }

}
